/***************************************************************************
 创建者: 华磊
 开始时间: 2018.8.14
 copyright: (C) 华友高科
 修改说明: (每次有修改就添加一条，带有 修改人，修改时间，修改描述)
 example (1) hualei 2017.5.8 类的具体实现代码编写

 ***************************************************************************/
#include "globalmanager.h"
#include "powermanager.h"
#include "robotcontrol.h"
#include "messagelog.h"
#include <qdir.h>
#include "robotmanager.h"
#include "batterymonitor.h"
#include "signal.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include "../ProgramEngine/programengine.h"
#include "robotengine.h"
#include "globalregister.h"
#include <QPixmap>
#define IF_DEBUG 0
#define D_PERIOD_CHECK_LICENSE 0
#define D_BATTERY_CONFIG_FILE_PATH "globalConfig/batteryConfig/batteryConfig.xml"
#define D_DATE_LOG_PATH "/var/local/datelog.xml"
<<<<<<< HEAD
#define D_MUSIC_VOLUME 1
=======

>>>>>>> origin/master

extern RobotControl* robCtl;
extern PowerManager *p_powerManger;
extern GlobalRegister *g_globalRegister;
BatteryMonitor* g_batteryMonitor=NULL;

GlobalManager::GlobalManager(int robId, RobotManager *robotManagerIn)
    :robotId(robId)
{

    isPlaySoudOnError=0;
    versionInfo.componentName="GlobalManager";
    versionInfo.componentVersion="V1.0";
    versionInfo.publishDate="2018.10.27";

    robotManager=robotManagerIn;
    enableControllerShutdown=true;
    batteryMonitor=NULL;
    debugFlag=0;

    Init();

}

GlobalManager::~GlobalManager()
{
    if(NULL!=sysInfoGet)
    {
        delete sysInfoGet;
        sysInfoGet = NULL;
    }
}

int GlobalManager::getBatteryPeakConfig(BatteryPeakConfig &configOut)
{
    return batteryMonitor->getBatteryPeakConfig(configOut);
}

int GlobalManager::setBatteryPeakConfig(BatteryPeakConfig configIn)
{
    return batteryMonitor->setBatteryPeakConfig(configIn);
}

int GlobalManager::setEthernetIpAddress(string netNameIn, string ipIn)
{

    QString systemCommand="ifconfig ";
    systemCommand+=QString::fromStdString(netNameIn);

    systemCommand+=" ";
    systemCommand+=QString::fromStdString(ipIn);
    systemCommand+=" netmask 255.255.255.0 &  ";

    qDebug()<<systemCommand;
    system(systemCommand.toLatin1().data());
    return 1;
}

int GlobalManager::getRobotImageStr(string filePathIn, string &imageStringOut)
{

    QString tmpString;
    getImageStringFromPath( QString::fromStdString(filePathIn),tmpString);
    imageStringOut=tmpString.toStdString();
    return 1;
}

int GlobalManager::changeComputerDate(string dayIn, string timeIn)
{
    QString systemCommand="date -s ";//date -s 2018-01-01
    systemCommand+=QString::fromStdString(dayIn);

    systemCommand+=" && date -s ";
    systemCommand+=QString::fromStdString(timeIn);
    systemCommand+=" && hwclock systohc &  ";

    qDebug()<<systemCommand;
    system(systemCommand.toLatin1().data());
    return 1;

}

int GlobalManager::changeComputerTime(string timeIn)
{
    int dateLefted=p_powerManger->getLicenseDayLefted();
    if(dateLefted<=0)
    {
        addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7017,-1,dateLefted);
        return -1;
    }
    QString systemCommand="date -s ";//date -s 23:01:01
    systemCommand+=QString::fromStdString(timeIn);
    systemCommand+=" && hwclock -w --systohc ";//系统时钟写入硬件时钟。
    systemCommand+=" && rm  ";
    systemCommand+=D_DATE_LOG_PATH;
    systemCommand+=" &";

//    qDebug()<<systemCommand;
    system(systemCommand.toLatin1().data());
    return 1;
}

int GlobalManager::setDebugFlag(int debugFlagIn)
{
    debugFlag=debugFlagIn;
    if(NULL!=batteryMonitor)
    {
         batteryMonitor->setDebugFlag(debugFlagIn);
    }
    return 1;
}

//分隔符有分号";" "&&" "||"。
//1、分号分隔：命令按顺序从左到右依次执行，如果某个命令执行出错了，直接跳到下一个命令继续执行！（这个比较危险，慎用）
//2、"&&"：这个和编程语言中的功能很相似，短路效果，如果某个命令执行出错了，后面的命令全部被忽略！
//3、"||"：忽略第一个有效命令后的所有命令。如果第一个命令就成功了，那后面的都被忽略；如果第一个命令失败，则继续执行第二个，如果第二个成功了，那后面的命令被忽略；以此类推..

int GlobalManager::upgradeWebHmi()
{
    qDebug()<<"GlobalManager::upgradeWebHmi";
    QString zipPath=WEB_HMI_DIRECTORY_PATH;
    zipPath+="html.zip";
    QFileInfo fileInfo(zipPath);
    if(false==fileInfo.isFile())
    {
        return -1;
    }


    QString systemCommand="rm -rf ";
    systemCommand+=WEB_HMI_DIRECTORY_PATH;
    systemCommand+="html/";

    systemCommand+=" && unzip -o ";
    systemCommand+=zipPath+" -d  "+WEB_HMI_DIRECTORY_PATH;
    systemCommand+=" && rm  ";
    systemCommand+=zipPath;

    QString changeAuothorityCommand=" && chmod -R 777 ";
    changeAuothorityCommand+=D_TCRCONTROLLER_ROOT_PATH;//加了＆后缀后，命令就是并行运行了。
//    changeAuothorityCommand+=" &";

    systemCommand+=changeAuothorityCommand;

    qDebug()<<systemCommand;
    system(systemCommand.toLatin1().data());

    //避免手动修改ｌｏｇｏ后又被解压覆盖
    QFile tmpFile;
    tmpFile.remove(zipPath);


    return 1;
}

int GlobalManager::getSerialPortListInfo(QStringList &ListOut)
{
    QSerialPortInfo serialPortInfo;

    foreach ( serialPortInfo, serialPortInfo.availablePorts() )
    {
        QString tmpString;
        tmpString+="serialNumber串序列号  :"+serialPortInfo.serialNumber();
        tmpString+="  ,portName :"+serialPortInfo.portName();
        tmpString+="  ,Description :"+serialPortInfo.description();
        tmpString+="  ,productIdentifier:"+QString::number(serialPortInfo.productIdentifier());
        ListOut.append(tmpString);

        qDebug() << "portName : " << serialPortInfo.portName();
        qDebug() << "Description : " << serialPortInfo.description();
        qDebug() << "serialNumber: " << serialPortInfo.serialNumber();
        qDebug() << "productIdentifier: " << serialPortInfo.productIdentifier();
    }
    return 1;
}

int GlobalManager::getRobotLogFileInfo(const int &robotIdIn, std::vector<Message> &messagesLogOut)
{
    Q_UNUSED(robotIdIn);
    QString filePath = QString(D_TCRCONTROLLER_DATA_PATH) + QString("globalConfig/logFile/robotLog.xml");

    DomParser domParser;
    // 打开robotLog.xml文件
    bool ok = domParser.openXml(filePath, QIODevice::ReadOnly );
    if( !ok )
    {
       // 打开失败
       qDebug()<<"error no log file";
       return OPERATE_ERROR;
    }

    // 查找日志信息主节点
    QDomNode  mainNode = domParser.findSubNode(domParser.getRootDomElement(), "log", ok );
    if( !ok )
    {
       qDebug()<<"error no log node";
       return OPERATE_ERROR;
    }

    // 获取子节点列表
    QDomNodeList devNodes = mainNode.childNodes();

    // 设置容器大小
    messagesLogOut.resize(devNodes.size());

    // 遍历获取子节点日志信息
    for (int i=0;i<devNodes.size();i++)
    {
       // 读取日志文件节点内容
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "messageLevel", ok ), messagesLogOut[i].MessageLevel );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "timeLong", ok ), messagesLogOut[i].time );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "robotId", ok ), messagesLogOut[i].robotId );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "componentClassName", ok ),
                          messagesLogOut[i].componentClassName );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "messageType", ok ), messagesLogOut[i].messageType );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "messageCode", ok ), messagesLogOut[i].messageCode );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "parameter1", ok ), messagesLogOut[i].parameter1 );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "parameter2", ok ), messagesLogOut[i].parameter2 );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "parameter3", ok ), messagesLogOut[i].parameter3 );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "parameter4", ok ), messagesLogOut[i].parameter4 );
       domParser.readXml( domParser.findSubNode(devNodes.at(i), "messageInformation", ok ),
                          messagesLogOut[i].MessageInformation );

    }

    domParser.closeXml();

    return OPERATE_OK;
}

int GlobalManager::changeFileDirectorAuthority()
{
    qDebug()<<"GlobalManager::changeFileDirectorAuthority()";
    QString systemCommand="chmod -R 777  ";
    systemCommand+=D_TCRCONTROLLER_ROOT_PATH;
    systemCommand+="&";
    system(systemCommand.toLatin1().data());
//    QMessageBox::information(NULL, "information", "修改文件夹权限完成！", QMessageBox::Yes );
    return 1;
}

int GlobalManager::removeRobotProgramFile(int robotIdIn, string fileName, int &returnFlag)
{
    QString filePath = QString(D_TCRCONTROLLER_DATA_PATH) + QString(ROBOT_COMMON_NAME) + QString::number(robotIdIn) + QString(ROBOT_PROGRAM_FLODER) + QString::fromStdString(fileName);
    QFile removeFile(filePath);

    if(removeFile.exists())
    {
        // 删除文件前要先关闭文件，否则无法删除
        removeFile.close();
        if(removeFile.remove())
        {
            returnFlag = 0;
        }
        else
        {
            returnFlag = -1;
        }
    }
    else
    {
        returnFlag = -1;
    }
}

int GlobalManager::removeMapFile(string fileName, int &returnFlag)
{
    QString  mapName=QString::fromStdString(fileName);

    QRegExp rx("(.*).yaml");
//    programStr.indexOf(rx);

    bool isMatch=rx.exactMatch(mapName);

    if(false==isMatch )
    {
        qDebug()<<"map file name error "<<mapName;
        returnFlag = -1;
        return -1;
    }



    QString mapOriginalName=rx.cap(1);


    //yaml file
    QString filePath = D_MAP_PATH + mapName;
    QFile removeFile(filePath);
    if(removeFile.exists())
    {
        qDebug()<<"remove "<<filePath;
        // 删除文件前要先关闭文件，否则无法删除
        removeFile.close();
        removeFile.remove();
    }

    //pgm file
    filePath = D_MAP_PATH + mapOriginalName+".pgm";
    QFile removeFile2(filePath);
    if(removeFile2.exists())
    {
        qDebug()<<"remove "<<filePath;
        // 删除文件前要先关闭文件，否则无法删除
        removeFile2.close();
        removeFile2.remove();
    }

    //ref file
    filePath = D_MAP_PATH + mapOriginalName+".ref";
    QFile removeFile3(filePath);
    if(removeFile3.exists())
    {
        qDebug()<<"remove "<<filePath;
        // 删除文件前要先关闭文件，否则无法删除
        removeFile3.close();
        removeFile3.remove();
    }

    //mjson file
    filePath = D_MAP_PATH + mapOriginalName+".mjson";
    QFile removeFile4(filePath);
    if(removeFile4.exists())
    {
        qDebug()<<"remove "<<filePath;
        // 删除文件前要先关闭文件，否则无法删除
        removeFile4.close();
        removeFile4.remove();
    }

    //pbstream file
    filePath = D_MAP_PATH + mapOriginalName+".pbstream";
    QFile removeFile5(filePath);
    if(removeFile5.exists())
    {
        qDebug()<<"remove "<<filePath;
        // 删除文件前要先关闭文件，否则无法删除
        removeFile5.close();
        removeFile5.remove();
    }

    returnFlag = 0;
    return 1;

}

int GlobalManager::readRobotProgramFile(int robotIdIn, string fileName, std::vector <std::string> &fileStringListOut)
{
    //hualei todo
    // 判断文件名是否为空
    fileStringListOut.clear();
    QString filePath = QString(D_TCRCONTROLLER_DATA_PATH) + QString(ROBOT_COMMON_NAME)
            + QString::number(robotIdIn) +QString(ROBOT_PROGRAM_FLODER) + QString::fromStdString(fileName);
    if(fileName.empty())
    {
         qDebug() << "Error !!! GlobalManager::readRobotProgramFile :" << filePath << " Is Empty!";
         return -1;
    }

    // 创建文件对象
    QFile programFile(filePath);
    // 只读形式打开文本文件
    if(!programFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Error !!! GlobalManager::readRobotProgramFile :" << filePath << " " + programFile.errorString();
        programFile.close();
        return -1;
    }

    qDebug() << "GlobalManage::readRobotProgramFile :" << filePath;
    fileStringListOut.clear();

    // 读取文件
    programFile.reset();
    QTextStream in(&programFile);
    while(!in.atEnd())
    {
       fileStringListOut.push_back(in.readLine().toStdString());
    }

    programFile.close();
    programFile.flush();//必须加，如果不加，可能关机的时候丢失文件内容。

    return 0;
}

int GlobalManager::writeRobotProgramFile(int robotIdIn, string fileName, std::vector <std::string> fileStringIn, int &returnFlag)
{
    //hualei todo
    QString filePath = QString(D_TCRCONTROLLER_DATA_PATH) + QString(ROBOT_COMMON_NAME) + QString::number(robotIdIn) +QString(ROBOT_PROGRAM_FLODER) + QString::fromStdString(fileName);
    if(fileName.empty())
    {
         qDebug() << "Error !!! GlobalManager::writeRobotProgramFile :" << filePath << " Is Empty!";
         returnFlag = -1;
         return -1;
    }

    // 创建文件对象
    QFile programFile(filePath);
    programFile.resize(0);
    // 只读形式打开文本文件
    if(!programFile.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        qDebug() << "Error !!! GlobalManager::writeRobotProgramFile :" << filePath << " " + programFile.errorString();
        returnFlag = -1;
        return -1;
    }
    else
    {
        qDebug() << "GlobalManage::writeRobotProgramFile :" << filePath;

        QTextStream in(&programFile);

        for(int i = 0; i < (int)fileStringIn.size(); i++)
        {
            if(QString::fromStdString(fileStringIn[i]).contains("\n"))
            {
                QString::fromStdString(fileStringIn[i]).replace("\n","");
            }
            in << QString::fromStdString(fileStringIn[i]) <<"\n";
        }

        returnFlag = 0;
        programFile.close();
        programFile.flush();//必须加，如果不加，可能关机的时候丢失文件内容。
    }

    return 0;
}

int GlobalManager::set_di_name_info(int robotIdIn, int indexIn, std::string nameIn, int &returnFlag)
{
    // 设置DI注释内容
    set_IO_NameInfo(robotIdIn, E_IoValueType_DI, indexIn, nameIn, returnFlag);
    if(returnFlag == 0)
    {
        // 设置成功
        qDebug() << "Set DI-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Success!";
        return 0;
    }
    else
    {
        // 设置失败
        qDebug() << "Set DI-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Failed!";
        returnFlag = -1;
        return -1;
    }
}

int GlobalManager::set_do_name_info(int robotIdIn, int indexIn, std::string nameIn, int &returnFlag)
{
    // 设置DO注释内容
    set_IO_NameInfo(robotIdIn, E_IoValueType_DO, indexIn, nameIn, returnFlag);
    if(returnFlag == 0)
    {
        // 设置成功
        qDebug() << "Set DO-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Success!";
        return 0;
    }
    else
    {
        // 设置失败
        qDebug() << "Set DO-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Failed!";
        returnFlag = -1;
        return -1;
    }
}

int GlobalManager::set_ai_name_info(int robotIdIn, int indexIn, string nameIn, int &returnFlag)
{
    // 设置AI注释内容
    set_IO_NameInfo(robotIdIn, E_IoValueType_AI, indexIn, nameIn, returnFlag);
    if(returnFlag == 0)
    {
        // 设置成功
        qDebug() << "Set AI-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Success!";
        return 0;
    }
    else
    {
        // 设置失败
        qDebug() << "Set AI-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Failed!";
        returnFlag = -1;
        return -1;
    }

}

int GlobalManager::set_ao_name_info(int robotIdIn, int indexIn, string nameIn, int &returnFlag)
{
    // 设置AO注释内容
    set_IO_NameInfo(robotIdIn, E_IoValueType_AO, indexIn, nameIn, returnFlag);
    if(returnFlag == 0)
    {
        // 设置成功
        qDebug() << "Set AO-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Success!";
        return 0;
    }
    else
    {
        // 设置失败
        qDebug() << "Set AO-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Failed!";
        returnFlag = -1;
        return -1;
    }
}

int GlobalManager::set_si_name_info(int robotIdIn, int indexIn, string nameIn, int &returnFlag)
{
    // 设置SI注释内容
    set_IO_NameInfo(robotIdIn, E_IoValueType_SI, indexIn, nameIn, returnFlag);
    if(returnFlag == 0)
    {
        // 设置成功
        qDebug() << "Set SI-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Success!";
        return 0;
    }
    else
    {
        // 设置失败
        qDebug() << "Set SI-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Failed!";
        returnFlag = -1;
        return -1;
    }
}

int GlobalManager::set_so_name_info(int robotIdIn, int indexIn, string nameIn, int &returnFlag)
{
    // 设置AI注释内容
    set_IO_NameInfo(robotIdIn, E_IoValueType_SO, indexIn, nameIn, returnFlag);
    if(returnFlag == 0)
    {
        // 设置成功
        qDebug() << "Set SO-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Success!";
        return 0;
    }
    else
    {
        // 设置失败
        qDebug() << "Set SO-Index:" << QString::number(indexIn) << "Name:" << QString::fromStdString(nameIn) << " Failed!";
        returnFlag = -1;
        return -1;
    }

}

int GlobalManager::get_di_name_info(int robotIdIn, std::vector<string> &namesOut)
{
<<<<<<< HEAD
    int returnFlag = get_Control_IO_NamesInfo(robotIdIn, E_IoValueType_DI, namesOut);
    if(returnFlag == SUCCESS)
    {
        // 设置成功
        qDebug() << "Get DI-Names === " << " Success!";
        return SUCCESS;
    }
    else
    {
        // 设置失败
        qDebug() << "Get DI-Names === " << " Failed!";
        return FAILED;
    }
=======
    int errorCode = 0;
    bool ok = false;
    DomParser domParser;
    QString xmlfile = QString(D_TCRCONTROLLER_DATA_PATH)+QString(ROBOT_COMMON_NAME) + QString::number(robotIdIn) + QString(CONFIG_STRING) + "iomap.xml";


    ok = domParser.openXml(xmlfile, QFile::ReadOnly | QFile::Text);

    if(!ok)
    {
        qDebug()<< "ERROR: openXml :"  << xmlfile;
        errorCode = -1;
        return errorCode;
    }

    do
    {

        QString ioDataMap = "";

        QString diName = "";
        int logicValueIndex = 0;
        QDomNode noteItem =  domParser.getRootDomElement().firstChild();
        while (!noteItem.isNull ()) {

            if (noteItem.isElement ()) {

                //将其转换为元素

                diName = "";
                QDomElement elementItem = noteItem.toElement ();

                //返回元素标记和id属性的值，tagName()来获取元素节点的标签名，attribute()来获取元素节点指定的属性的值，

                qDebug()<<elementItem.text() << elementItem.tagName ();

                if(elementItem.tagName().compare("IO") == 0)
                {
                    if(elementItem.attribute("valueType").toInt() == 1)
                    {
                        diName=elementItem.text();

                        logicValueIndex = elementItem.attribute("logicValueIndex").toInt();
                        if(logicValueIndex>0)
                        {
                            if(logicValueIndex >= namesOut.size())
                            {
                                namesOut.resize(logicValueIndex);
                            }
                            logicValueIndex -= 1;
                            namesOut[logicValueIndex] = diName.toStdString();
                        }
                    }
                }
            }
            noteItem = noteItem.nextSibling ();//nextSibling()获取下一个兄弟节点
        }
    }
    while(0);
    closeXml();
    return errorCode;

>>>>>>> origin/master
}

int GlobalManager::get_do_name_info(int robotIdIn, std::vector<string> &namesOut)
{
<<<<<<< HEAD
    int returnFlag = get_Control_IO_NamesInfo(robotIdIn, E_IoValueType_DO, namesOut);
    if(returnFlag == SUCCESS)
    {
        // 设置成功
        qDebug() << "Get DO-Names === " << " Success!";
        return SUCCESS;
    }
    else
    {
        // 设置失败
        qDebug() << "Get DO-Names === " << " Failed!";
        return FAILED;
    }

}

int GlobalManager::get_ai_name_info(int robotIdIn, std::vector<string> &namesOut)
{
    int returnFlag = get_Control_IO_NamesInfo(robotIdIn, E_IoValueType_AI, namesOut);
    if(returnFlag == SUCCESS)
    {
        // 设置成功
        qDebug() << "Get AI-Names === " << " Success!";
        return SUCCESS;
    }
    else
    {
        // 设置失败
        qDebug() << "Get AI-Names === " << " Failed!";
        return FAILED;
    }
}

int GlobalManager::get_ao_name_info(int robotIdIn, std::vector<string> &namesOut)
{
    int returnFlag = get_Control_IO_NamesInfo(robotIdIn, E_IoValueType_AO, namesOut);
    if(returnFlag == SUCCESS)
    {
        // 设置成功
        qDebug() << "Get AO-Names === " << " Success!";
        return SUCCESS;
    }
    else
    {
        // 设置失败
        qDebug() << "Get AO-Names === " << " Failed!";
        return FAILED;
    }
}

int GlobalManager::get_si_name_info(int robotIdIn, std::vector<string> &namesOut)
{
    int returnFlag = get_Control_IO_NamesInfo(robotIdIn, E_IoValueType_SI, namesOut);
    if(returnFlag == SUCCESS)
    {
        // 设置成功
        qDebug() << "Get SI-Names === " << " Success!";
        return SUCCESS;
    }
    else
    {
        // 设置失败
        qDebug() << "Get SI-Names === " << " Failed!";
        return FAILED;
    }
}

int GlobalManager::get_so_name_info(int robotIdIn, std::vector<string> &namesOut)
{
    int returnFlag = get_Control_IO_NamesInfo(robotIdIn, E_IoValueType_SO, namesOut);
    if(returnFlag == SUCCESS)
    {
        // 设置成功
        qDebug() << "Get SO-Names === " << " Success!";
        return SUCCESS;
    }
    else
    {
        // 设置失败
        qDebug() << "Get SO-Names === " << " Failed!";
        return FAILED;
    }
}

int GlobalManager::get_All_IO_NamesInfo(int robotId, struct IOMapNamesInfo &nameOut)
{
//    nameOut.resize(7);//null di do ai ao si so
    QString fileName = QString(D_TCRCONTROLLER_DATA_PATH)+QString(ROBOT_COMMON_NAME) + QString::number(robotId)
                        + QString(CONFIG_STRING) + "iomap.xml";
     QFile *file = new QFile();
     file->setFileName(fileName);

     if(file->isOpen())
     {
         qDebug()<<"==========XmlParse===file already open======"<<"\n\n\n";
         file->reset();
         file->close();
     }
     if(!file->open(QFile::ReadWrite | QFile::Text))
     {
         //消息预留
         //打开ｘｍｌ文件失败
         qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->file.open->%s\n") << fileName;
         return -1;
     }

     QDomDocument m_doc;
     // 设置内容
     if(!m_doc.setContent(file))
     {
         //消息预留
         //ｘｍｌ文件格式不正确
          qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->doc.setContent\n");
          file->close();
          return -1;
     }
     file->close();
//     file->reset();

    QDomElement root = m_doc.documentElement();
    if("IoDataMap" == root.tagName())
    {
        // 获取子节点列表
        QDomNodeList lists = root.childNodes();

        for(int i = 0;i<lists.count();i++)
        {
            // 获取其中一个子节点
            QDomNode ioData = lists.at(i);
            // 获取子节点元素
            QDomElement ele = ioData.toElement();

            // 获取子节点元素属性值
            /********* DI *********/
            if(ele.attribute("valueType").toInt() == E_IoValueType_DI)
            {
                nameOut.diNamesInfo.push_back(ele.firstChild().nodeValue().toStdString());
            }

            /********* DO *********/
            if(ele.attribute("valueType").toInt() == E_IoValueType_DO)
            {
                nameOut.doNamesInfo.push_back(ele.firstChild().nodeValue().toStdString());
            }

            /********* AI *********/
            if(ele.attribute("valueType").toInt() == E_IoValueType_AI)
            {
                nameOut.aiNamesInfo.push_back(ele.firstChild().nodeValue().toStdString());
            }

            /********* AO *********/
            if(ele.attribute("valueType").toInt() == E_IoValueType_AO)
            {
                nameOut.aoNamesInfo.push_back(ele.firstChild().nodeValue().toStdString());
            }

            /********* SI *********/
            if(ele.attribute("valueType").toInt() == E_IoValueType_SI)
            {
                nameOut.siNamesInfo.push_back(ele.firstChild().nodeValue().toStdString());
            }

            /********* SO *********/
            if(ele.attribute("valueType").toInt() == E_IoValueType_SO)
            {
                nameOut.soNamesInfo.push_back(ele.firstChild().nodeValue().toStdString());
            }
        }
    }
    return 0;
}

int GlobalManager::set_IO_NameInfo(int robotIdIn, int IOValueTypeIn, int logicValueIndexIn, string nameIn, int &returnFlag)
{
    QString ioMapFilePath = QString(D_TCRCONTROLLER_DATA_PATH)+QString(ROBOT_COMMON_NAME)
                                + QString::number(robotIdIn) + QString(CONFIG_STRING) + "iomap.xml";
    QFile IOMapFile(ioMapFilePath);

    if(IOMapFile.isOpen())
    {
        IOMapFile.reset();
        IOMapFile.close();
    }
    // 读写方式打开文件
    if(!IOMapFile.open(QFile::ReadWrite | QFile::Text))
    {
        // 打开失败
        qDebug() << "GlobalManager::set_IO_NameInfo Open File:" << ioMapFilePath << " ======= Failed!";
        returnFlag = OPERATE_ERROR;
        return OPERATE_ERROR;
    }

    QDomDocument iomap_Doc;
    // 设置内容
    if(!iomap_Doc.setContent(&IOMapFile))
    {
        // 设置文件内容失败
        qDebug() << "GlobalManager::set_IO_NameInfo Open File:" << ioMapFilePath << " ======= setContent Failed!";
        returnFlag =OPERATE_ERROR;
        IOMapFile.close();
        return OPERATE_ERROR;
    }
    // 文件一定要关闭,否则会有操作失败
    IOMapFile.close();

    // 读取解析文件
    if(iomap_Doc.documentElement().tagName() == "IoDataMap")
    {
        // 获取子节点列表
        QDomNodeList nodeList = iomap_Doc.documentElement().childNodes();

        for(int i = 0; i < nodeList.size(); i++)
        {
            // 匹配IO类型
            if(nodeList.at(i).toElement().attribute("valueType").toInt() == IOValueTypeIn)
            {
                // 匹配逻辑值索引
                if(nodeList.at(i).toElement().attribute("logicValueIndex").toInt() == logicValueIndexIn)
                {
                    // 设置内容
                    iomap_Doc.documentElement().childNodes().at(i).firstChild().setNodeValue(QString::fromStdString(nameIn));
                    // 设置完成保存文件
                    IOMapFile.setFileName(ioMapFilePath);
                    if(!IOMapFile.open(QFile::WriteOnly | QFile::Truncate))
                    {
                        returnFlag =OPERATE_ERROR;
                        IOMapFile.close();
                        return OPERATE_ERROR;
                    }

                    QTextStream fileTs(&IOMapFile);
                    fileTs.reset();
                    fileTs.setCodec("utf-8");
                    iomap_Doc.save(fileTs,4, QDomNode::EncodingFromTextStream);
                    IOMapFile.close();

                    qDebug() << "NodeType:" << IOValueTypeIn << "logicValueIndex:" << logicValueIndexIn << "Value:" << nodeList.at(i).firstChild().nodeValue();
                    returnFlag = OPERATE_OK;
                    break;
                }
                // 没有找到逻辑值索引
                else
                {
                    returnFlag =OPERATE_ERROR;
                    IOMapFile.close();
                }
            }
            // 没找到IO类型
            else
            {
                returnFlag =OPERATE_ERROR;
                IOMapFile.close();
            }
        }
    }
    else
    {
        returnFlag =OPERATE_ERROR;
        IOMapFile.close();
        return OPERATE_ERROR;
    }

    IOMapFile.close();
    // 防止程序异常关机时,数据丢失
    IOMapFile.flush();
    return returnFlag;
=======
    //todo
    int errorCode = 0;
    bool ok = false;
    DomParser domParser;
    QString xmlfile = QString(D_TCRCONTROLLER_DATA_PATH)+QString(ROBOT_COMMON_NAME) + QString::number(robotIdIn) + QString(CONFIG_STRING) + "iomap.xml";
    ok = domParser.openXml(xmlfile, QFile::ReadOnly | QFile::Text);

    if(!ok)
    {
        qDebug()<< "ERROR: openXml :"  << xmlfile;
        errorCode = -1;
        return errorCode;
    }

    do
    {

        QString ioDataMap = "";

        namesOut.clear();

        QString doName = "";
        int logicValueIndex = 0;
        QDomNode noteItem =  domParser.getRootDomElement().firstChild();
        while (!noteItem.isNull ()) {

            if (noteItem.isElement ()) {

                //将其转换为元素
                doName = "";
                QDomElement elementItem = noteItem.toElement ();
                //返回元素标记和id属性的值，tagName()来获取元素节点的标签名，attribute()来获取元素节点指定的属性的值，

                qDebug()<<elementItem.text() << elementItem.tagName ();

                if(elementItem.tagName().compare("IO") == 0)
                {
                    if(elementItem.attribute("valueType").toInt() == 2)
                    {
                        doName=elementItem.text();

                        logicValueIndex = elementItem.attribute("logicValueIndex").toInt();
                        if(logicValueIndex>0)
                        {
                            if(logicValueIndex >= namesOut.size())
                            {
                                namesOut.resize(logicValueIndex);
                            }
                            logicValueIndex -= 1;
                            namesOut[logicValueIndex] = doName.toStdString();
                        }
                    }
                }
            }
            noteItem = noteItem.nextSibling ();//nextSibling()获取下一个兄弟节点
        }
    }
    while(0);
    domParser.closeXml();

    return errorCode;

>>>>>>> origin/master
}

int GlobalManager::getRobotProgramFileList(int robotIdIn, std::vector<string> &programFileListOut)
{
    qDebug()<<"getRobotProgramFileList";


    QString path=D_TCRCONTROLLER_DATA_PATH;
     path= path+ROBOT_COMMON_NAME+QString::number( robotIdIn )+"/program/";

    QDir dir(path);
    qDebug()<<"path="<<dir;
    QStringList nameFilters;
    nameFilters << "*.txt" ;
    QStringList files = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);
    qDebug()<<"files="<<files;
    programFileListOut.resize(files.size());
    for(int i=0;i<files.size();i++)
    {
        programFileListOut[i]=files[i].toStdString();
    }
    return 1;
}

int GlobalManager::getBatteryInfo(BatteryInformation &batteryInfoOut)
{
    return batteryMonitor->getBatteryInfo(batteryInfoOut);
}

int GlobalManager::restartNfsService()
{
    qDebug()<<"GlobalManager::restartNfsService()";
    QString systemCommand="service nfs-kernel-server restart  &";
    system(systemCommand.toLatin1().data());
    qDebug()<<systemCommand;
    return 1;
}

int GlobalManager::getFileList(int pathType, QVector<QString> &fileList)
{
    qDebug()<<"GlobalManager::getFileList begin,pathType="<<pathType;

    QString path;
    QStringList nameFilters;
    switch (pathType)
    {
        case E_FILEPATH_TYPE_PC_HARDDISK_BACKUP:
            {
                path=PC_HARD_DISK_BACKUP_PATH;

                nameFilters << "*.zip" ;
            }
            break;
        case E_FILEPATH_TYPE_PC_USBDISK_BACKUP:
            {
                path=PC_U_DISK_BACKUP_PATH;

                nameFilters << "*.zip" ;
            }
            break;
    case E_FILEPATH_TYPE_AGV_MUSIC:
        {
            path=MUSIC_FILEPATH;

            nameFilters << "*.mp3" ;
        }
        break;

        default:
            {
                return -1;
            }
            break;
    }

    QDir dir(path);
    qDebug()<<"path="<<dir;
    QStringList files = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);
    qDebug()<<"files="<<files;
    fileList.resize(files.size());
    for(int i=0;i<files.size();i++)
    {
        fileList[i]=files[i];
    }
    return 1;

}



int GlobalManager::backupFile(int backUpType, int diskType, QString fileName, int robotId)
{
    qDebug()<<"GlobalManager::backupFile begin,backUpType="<<backUpType<<"diskType="<<diskType
           <<"fileName="<<fileName<<"robotId="<<fileName;
    QString systemCommand;
    QString diskPath;
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("-yyyy-MM-dd-hh-mm");
    if(E_STORAGE_TYPE_PC_HARDDISK==diskType)
    {
        diskPath=PC_HARD_DISK_BACKUP_PATH;
    }
    else  if(E_STORAGE_TYPE_PC_USBDISK==diskType)
    {
        diskPath=PC_U_DISK_BACKUP_PATH;//TODO
    }
    QString sourcePath;
    switch (backUpType)
    {
        case E_BACKUP_TYPE_BIN:
            {
                sourcePath=TCR_CONTROLLER_BIN_PATH;
            }
            break;
        case E_BACKUP_TYPE_GLOBALCONFIG:
            {
                sourcePath=D_TCRCONTROLLER_WORK_PATH;
                sourcePath+="data/globalConfig";
            }
            break;
        case E_BACKUP_TYPE_ROBOTCONFIG:
            {
                sourcePath=D_TCRCONTROLLER_WORK_PATH;
                sourcePath+="data/robotData"+QString::number(robotId)+"/config";
            }
            break;
        case E_BACKUP_TYPE_ROBOT_ALL_PROGRAM:
            {
                sourcePath=D_TCRCONTROLLER_WORK_PATH;
                sourcePath+="data/robotData"+QString::number(robotId)+"/program";
            }
            break;
        case E_BACKUP_TYPE_ROBOT_COORDINATE_DATA:
            {
                sourcePath=D_TCRCONTROLLER_WORK_PATH;
                sourcePath+="data/robotData"+QString::number(robotId)+"/dat";
            }
            break;
        case E_BACKUP_TYPE_ROBOT_ONE_PROGRAM:
            {
                sourcePath=D_TCRCONTROLLER_WORK_PATH;
                sourcePath+="data/robotData"+QString::number(robotId)+"/program/"+fileName;
            }
            break;
        case E_BACKUP_TYPE_ALL_FILES:
            {
                sourcePath=D_TCRCONTROLLER_WORK_PATH;
            }
            break;
        default:
            {
                return -1;
            }
            break;
    }


    systemCommand="zip -r ";
    systemCommand+=diskPath+fileName+current_date+".zip"+" "+sourcePath+" &";
    qDebug()<<systemCommand;
    system(systemCommand.toLatin1().data());
    return 1;

}

int GlobalManager::restoreFile(int backUpType,int diskType, QString fileName, int robotId)
{
    qDebug()<<"GlobalManager::restoreFile begin,backUpType="<<backUpType<<"diskType="<<diskType
           <<"fileName="<<fileName<<"robotId="<<fileName;
    QString systemCommand;
    QString diskPath;
    if(E_STORAGE_TYPE_PC_HARDDISK==diskType)
    {
        diskPath=PC_HARD_DISK_BACKUP_PATH;
    }
    else  if(E_STORAGE_TYPE_PC_USBDISK==diskType)
    {
        diskPath=PC_U_DISK_BACKUP_PATH;//TODO
    }

    systemCommand="unzip -o ";
    systemCommand+=diskPath+fileName+" -d  /"+" &";
    qDebug()<<systemCommand;
    system(systemCommand.toLatin1().data());

    systemCommand="chmod -R 777 ";
    systemCommand+=D_TCRCONTROLLER_WORK_PATH;
    systemCommand+=" &";
    qDebug()<<systemCommand;
    system(systemCommand.toLatin1().data());


    return 1;

}


void GlobalManager::Init()
{

    readConfigFile();
    readDateFromXmlFile(D_DATE_LOG_PATH);

    startDateTime = QDateTime::currentDateTime();
    //md5Instance = MD5Check::getInstance();
    ioServoOnFlag = false;

    if(0 == firstTimeFlag)
    {
        firstStartTime = QDateTime::currentDateTime();
        writeFirstTimeFlag();
    }
    else
    {

        readOldData();
    }

    getSystemInfo();

    createThread();
    readStartType();
    globalRegister=new GlobalRegister;
    initGlobalRegValue(machineStartType);
    g_globalRegister=globalRegister;

    QString batteryConfigFilePath=D_TCRCONTROLLER_DATA_PATH;
    batteryConfigFilePath+=D_BATTERY_CONFIG_FILE_PATH;
    batteryMonitor= new BatteryMonitor(batteryConfigFilePath);
    g_batteryMonitor=batteryMonitor;
    if(false==batteryMonitor->isInitalOk())
    {
        qDebug()<<"error, batteryMonitor  error";
        addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7008,robotId);

    }
    upgradeWebHmi();
    changeFileDirectorAuthority();

}

int GlobalManager::readVersion(std::vector <ComponentVersion> &componentVersionList)
{
    componentVersionList.push_back(versionInfo);
    return 1;
}

int GlobalManager::getHardDiskInfo(double & totalVolume, double & freeVolume)
{
    totalVolume=hardDiskSize;
    freeVolume=hardDiskFree;
    return 1;
}

int GlobalManager::getRamInfo(double & totalVolume, double & freeVolume)
{
    totalVolume=memorySize;
    freeVolume=ramFree;
    return 1;
}

int GlobalManager::getCpuInfo(double & usedRatio)
{
   usedRatio=cpuUsedRatio;
   return 1;
}

int GlobalManager::updateHardDiskInfo()
{
    readHardDiskInfo(hardDiskSize,hardDiskFree);
    hardDiskUsage=(hardDiskSize-hardDiskFree)/hardDiskSize;
    return 1;
}

int GlobalManager::updateRamInfo()
{

    readRamInfo(memorySize,ramFree);
    memoryUsage=(memorySize-ramFree)/memorySize;
    return 1;
}

int GlobalManager::updateCpuInfo()
{
   readCpuInfo(cpuUsedRatio);
   return 1;
}

int GlobalManager::readHardDiskInfo(double & totalVolume, double & freeVolume)
{
    DEV_MEM devInfo;
    devInfo=memoryInfo.get_devmem2();
    totalVolume=devInfo.total;
    freeVolume=devInfo.total*(1-devInfo.used_rate);
    return 1;
}

int GlobalManager::readRamInfo(double & totalVolume, double & freeVolume)
{
    MEM_PACK devInfo;
    devInfo=memoryInfo.get_memoccupy();
    totalVolume=devInfo.total;
    freeVolume=devInfo.total*(1-devInfo.used_rate);
    return 1;
}

int GlobalManager::readCpuInfo(double & usedRatio)
{
   usedRatio=memoryInfo.getCpuRate();
   return 1;
}

int GlobalManager::writeStartTypeToFile()
{
    QString tmpFilePath = D_TCRCONTROLLER_DATA_PATH;
    tmpFilePath+=GLOBAL_START_TYPE;
    bool writeOk = openXml(tmpFilePath);

    QString writeEle = "startType";
    if(writeOk)
    {
        writeXml(writeEle,machineStartType);
        closeWriteXml(tmpFilePath);
    }
    else
    {
        qDebug() << "error:  GlobalManager::writeStartTypeToFile"<<"\n\n";
    }
    return 1;
}

int GlobalManager::setStartType(int type)
{
    qDebug() << "GlobalManager::setStartType type=="<<type;
    machineStartType=type;

    writeStartTypeToFile();

    return 1;
}



int GlobalManager::getStartType()
{
    return machineStartType;
}

int GlobalManager::readStartType()
{
    QString filePath = D_TCRCONTROLLER_DATA_PATH;
    filePath+=GLOBAL_START_TYPE;

    QString startStr = "startType";

    bool openFlag = openXml(filePath);
    if(openFlag)
    {
        readXml(startStr,machineStartType);
        closeReadXml();
    }
    else
    {
        qDebug() <<"startType error"<<"\n\n";
    }

    return machineStartType;


}

int GlobalManager::forceQuitProgram()
{

    int robotcount=robotManager->robotsMap.size();
    QList<int> keys= robotManager->robotsMap.keys();

    qDebug()<<"user force quit program!!!!!!!!!!!!!!!!!!!!!!!";
    addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7012,-1);

    //保存寄存器
    writeAllRegFile();

    //ecatShutdown
    robCtl->controllerShutDown();

    //robotManagerShutdown
    for(int i=0;i<keys.size(); i++ )
    {
        int tmpRobId = keys.at(i);
        robotManager->robotsMap.value(tmpRobId)->controllerShutDown();

    }

//     sleep(2);//wait for file save files;
//     raise(SIGINT);
//     sleep(1);//wait for file save files;

//     exit(0);

//    system("killall -9 agvBaseControl");
//    osShutDown(isReboot);

//    exit(EXIT_SUCCESS);

    return 1;
}

int GlobalManager::controllerShutDown(bool isReboot)
{

    if(false==enableControllerShutdown)
    {
        qDebug()<<"failed:::::false==enableControllerShutdown";
        return -100;
    }

    //日志保存
    MessageLog::getInstance()->timerSaveLogToFile();

    QList<int> keys= robotManager->robotsMap.keys();
    //判断是否有机器人在运行中
    for(int i=0;i<keys.size(); i++ )
    {
        int tmpRobId = keys.at(i);
        robotManager->robotsMap.value(tmpRobId)->resetProgram();
//        if(ENUM_COMMAND_RUN==robotManager->robotsMap.value(tmpRobId)->getRobotBasicStatus())
//        {
//            qDebug()<<"failed:::::controllerShutDown, robot is moving";
//            addMsg(ENUM_MSG_WARNING,"GlobalManager","GlobalManager",7004,tmpRobId);
//            return -101;
//        }

    }

    //保存寄存器
    writeAllRegFile();

    //ecatShutdown
    robCtl->controllerShutDown();

    //robotManagerShutdown
    for(int i=0;i<keys.size(); i++ )
    {
        int tmpRobId = keys.at(i);
        robotManager->robotsMap.value(tmpRobId)->controllerShutDown();

    }



    if(true==isReboot)
    {
        addMsg(ENUM_MSG_WARNING,"GlobalManager","GlobalManager",7007,robotId);
    }
    else
    {
        addMsg(ENUM_MSG_WARNING,"GlobalManager","GlobalManager",7005,robotId);
    }

    playSystemMusic("systemShutDown.mp3");

     sleep(5);//wait for file save files;

    //system("killall -9 TcrController");
    osShutDown(isReboot);

    return 1;
}

int GlobalManager::controlShutDownEnable(bool enable)
{
    enableControllerShutdown=enable;
    return 1;
}

#include <signal.h>
#include <sys/reboot.h>

void GlobalManager::osShutDown(bool isReboot)
{
//    /* first disable all our signals */
//    sigset_t set;
//    sigfillset(&set);
//    sigprocmask(SIG_BLOCK, &set, NULL);

//    /* send signals to all processes  _except_ pid 1 */
//    printf("sending SIGTERM signal to all processes\n");
//    kill(-1, SIGTERM);
//    sync();
//    sleep(3);

//    printf("sending SIGKILL signal to all processes\n");
//    kill(-1, SIGKILL);
//    sync();
//    sleep(3);

//    /* shutdown */
//    printf("system shutdown\n");
//    sleep(2);
//    if(true==isReboot)
//    {
//        reboot(RB_POWER_OFF);
//    }

    //-----------------------------
    if(true==isReboot)
    {
        qDebug()<<"shutdown -r now";
        system("shutdown -r now");
    }
    else
    {
        qDebug()<<"shutdown -h now";
        system("shutdown -h now");
    }

}


void GlobalManager::initGlobalRegValue(int startType)
{
   // qDebug() <<"*********GlobalManager::initGlobalRegValue*********"<<startType<<"\n\n\n\n";
    if(ROBOT_HOT_START == startType)
    {
        return  readRegRValue_fromFile();

    }
    else if(ROBOT_COOL_START == startType)
    {
        globalRegister->initGlobalRegValue();
        writeAllRegFile();

    }
    else
    {

        qDebug()<<"startType="<<startType<<"不支持";
        addMsg(ENUM_MSG_ERROR, "RegData", "RegData", 7006, robotId);
    }



}





int GlobalManager::clearAllRobotsAllRegister(int &returnFlag)
{
    clearRegRValue();

    int robotcount=robotManager->robotsMap.size();
    QList<int> keys= robotManager->robotsMap.keys();
    for(int i=0;i<keys.size(); i++ )
    {
        int tmpRobId = keys.at(i);
        robotManager->robotsMap.value(tmpRobId)->programEngine->regData->clearAllPrValue();
        robotManager->robotsMap.value(tmpRobId)->programEngine->regData->clearAllTimerValue();
        robotManager->robotsMap.value(tmpRobId)->programEngine->regData->clearAllRegRValue();
        robotManager->robotsMap.value(tmpRobId)->programEngine->regData->clearAllPlValue();
    }
    returnFlag = 0;
    return returnFlag;

}

void GlobalManager::writeFirstTimeFlag()
{
    int flag = 1;

    QString firstTimeFlagStr = D_TCRCONTROLLER_DATA_PATH;
    firstTimeFlagStr+=GLOBAL_BASEDATA;
    QString strConfigGroup = "";
    QString strConfigKey = "";

    QSettings settings(firstTimeFlagStr,QSettings::IniFormat);
    settings.setIniCodec("UTF-8");
    strConfigGroup = "SystemInfo";
    settings.beginGroup(strConfigGroup);

    strConfigKey = "firstTimeFlag";
    settings.setValue(strConfigKey,QVariant(flag));
    settings.endGroup();

}

int GlobalManager::readConfigFile()
{
    QVariant strConfigValue;
    QString firstTimeFlagStr = D_TCRCONTROLLER_DATA_PATH;
    firstTimeFlagStr+=GLOBAL_BASEDATA;
    QString strConfigGroup = "";
    QString strConfigKey = "";

    QSettings settings(firstTimeFlagStr,QSettings::IniFormat);
    settings.setIniCodec("UTF-8");
    strConfigGroup = "SystemInfo";
    settings.beginGroup(strConfigGroup);

    strConfigKey = "firstTimeFlag";
    strConfigValue = settings.value(strConfigKey);
    firstTimeFlag = strConfigValue.toInt();

    strConfigKey = "isPlaySoudOnError";
    strConfigValue = settings.value(strConfigKey);
    isPlaySoudOnError = strConfigValue.toInt();


    settings.endGroup();

    //qDebug() << "===firstFlag===="<<firstFlag<<"\n\n\n\n";
    return 1;
}


int GlobalManager::getSystemInfo()
{
    sysInfoGet = new SysInfoGet;

//    sysInfoGet->getSysInfo();

//    hardDiskSize = sysInfoGet->totalDiskSize;
//    hardDiskUsage = (sysInfoGet->usedDiskSize) / hardDiskSize;

//    memorySize = sysInfoGet->totalMemSize;
//    memoryUsage = (sysInfoGet->usedMemSize) / memorySize;

//    usbExist = sysInfoGet->usbExist;

//    usbSize = sysInfoGet->totalUsbSize;
//    usbUsage = (sysInfoGet->usedUsbSize) / usbSize;

    getAllTime();
}


int GlobalManager::getAllTime()
{
    currentDateTime = QDateTime::currentDateTime();

    totalStartMachineTime = firstStartTime.secsTo(currentDateTime);

    systemOnTime = startDateTime.secsTo(currentDateTime);

//     qDebug() << "****firstStartTime*****"<<firstStartTime.toString()<<"====currentDateTime===="<<currentDateTime.toString()
//              <<"====totalStartMachineTime===" <<totalStartMachineTime<<"-------startDateTime-----------"<<startDateTime
//             <<"***systemOnTime***"<<systemOnTime<<"===oldSystemOnTime====="<<oldSystemOnTime<<"\n\n\n\n\n";

    totalSystemOnTime = systemOnTime + oldSystemOnTime;

//    qDebug() << __FUNCTION__<<"****hardDisk***"<<hardDiskSize<<"***hardDiskUsage**"
//             <<hardDiskUsage<<"***memorySize****"<<memorySize<<"**memoryUsage***"<<memoryUsage
//             <<"****usbExist****"<<usbExist<<"***usbSize***"<<usbSize<<"***usbUsage***"<<usbUsage
//             <<"***systemOnTime***"<<systemOnTime << endl;

    transTimeToString();

//    qDebug() << "===systemOnTimeStr==="<<systemOnTimeStr<<"===totalSystemOnTimeStr==="<<totalSystemOnTimeStr
//             <<"****totalStartMachineTimeStr***"<<totalStartMachineTimeStr<<endl;
}

void GlobalManager::transTimeToString()
{
    //下面２处出现过QString coredump,是因为QString 类型的成员变量线程不安全，多线程进行了操作。

    int tmpYear;
    int tmpMonth;
    int tmpDay;
    int tmpHour;
    int tmpMinute;
    int tmpSecond;

    QString tmpDateStr = "-";
    QString tmpSpaceStr = "  ";
    QString tmpTimeStr = ":";

    int tmpTime = systemOnTime;

    tmpYear = tmpTime / YEAR_CONST;

    tmpTime = tmpTime - (tmpYear * YEAR_CONST);

    tmpMonth = tmpTime / MONTH_CONST;

    tmpTime = tmpTime - (tmpMonth * MONTH_CONST);

    tmpDay = tmpTime / DAY_CONST;

    tmpTime = tmpTime - (tmpDay * DAY_CONST);

    tmpHour = tmpTime / HOUR_CONST;

    tmpTime = tmpTime - (tmpHour * HOUR_CONST);

    tmpMinute = tmpTime  / MINUTE_CONST;

    tmpSecond = (tmpTime  - (tmpMinute* MINUTE_CONST));

    systemOnTimeStr = QString::number(tmpYear) + tmpDateStr + QString::number(tmpMonth) + tmpDateStr + QString::number(tmpDay)
            + tmpSpaceStr + QString::number(tmpHour) + tmpTimeStr + QString::number(tmpMinute) +
            tmpTimeStr + QString::number(tmpSecond);//hualei coredump ?不知道为什么

    tmpTime = totalSystemOnTime;

    tmpYear = tmpTime / YEAR_CONST;

    tmpTime = tmpTime - (tmpYear * YEAR_CONST);

    tmpMonth = tmpTime / MONTH_CONST;

    tmpTime = tmpTime - (tmpMonth * MONTH_CONST);

    tmpDay = tmpTime / DAY_CONST;

    tmpTime = tmpTime - (tmpDay * DAY_CONST);

    tmpHour = tmpTime / HOUR_CONST;

    tmpTime = tmpTime - (tmpHour * HOUR_CONST);

    tmpMinute = tmpTime  / MINUTE_CONST;

    tmpSecond = (tmpTime - (tmpMinute* MINUTE_CONST));

    //为什么会coredump?
    totalSystemOnTimeStr = QString::number(tmpYear) + tmpDateStr
            + QString::number(tmpMonth) + tmpDateStr + QString::number(tmpDay)
            + tmpSpaceStr + QString::number(tmpHour) + tmpTimeStr
            + QString::number(tmpMinute) + tmpTimeStr + QString::number(tmpSecond);

    tmpTime = totalStartMachineTime;

    tmpYear = tmpTime / YEAR_CONST;

    tmpTime = tmpTime - (tmpYear * YEAR_CONST);

    tmpMonth = tmpTime / MONTH_CONST;

    tmpTime = tmpTime - (tmpMonth * MONTH_CONST);

    tmpDay = tmpTime / DAY_CONST;

    tmpTime = tmpTime - (tmpDay * DAY_CONST);

    tmpHour = tmpTime / HOUR_CONST;

    tmpTime = tmpTime - (tmpHour * HOUR_CONST);

    tmpMinute = tmpTime  / MINUTE_CONST;

    tmpSecond = (tmpTime  - (tmpMinute* MINUTE_CONST));


    totalStartMachineTimeStr = QString::number(tmpYear) + tmpDateStr + QString::number(tmpMonth) + tmpDateStr + QString::number(tmpDay)
            + tmpSpaceStr + QString::number(tmpHour) + tmpTimeStr + QString::number(tmpMinute) + tmpTimeStr + QString::number(tmpSecond);


}

void GlobalManager::readOldData()
{
    //从文件中获取上次保存的系统总的上电时间
    //oldSystemOnTime

    QString tmpFilePath=D_TCRCONTROLLER_DATA_PATH;
    tmpFilePath+=GLOBAL_SYSTEM_FILE;
    QFile file(tmpFilePath);
    if(file.exists())
    {
        if(file.open(QIODevice::ReadOnly))
        {
            QDataStream out(&file);
            out.setVersion(QDataStream::Qt_4_6);

            out >> oldSystemOnTime;

            out >> firstStartTime;

            file.close();
            file.flush();//必须加，如果不加，可能关机的时候丢失文件内容。
        }
    }
    else
    {
        //消息预留
        //获取系统信息失败

    }
}

void GlobalManager::saveSystemData()
{
    QString tmpFilePath=D_TCRCONTROLLER_DATA_PATH;
    tmpFilePath+=GLOBAL_SYSTEM_FILE;
    QFile file(tmpFilePath);

    if(file.exists())
    {
        if(file.open(QIODevice::ReadWrite))
        {
            QDataStream in(&file);
            in.setVersion(QDataStream::Qt_4_6);

            in << totalSystemOnTime;

            in << firstStartTime;

            file.close();
            file.flush();//必须加，如果不加，可能关机的时候丢失文件内容。

        }
    }
    else
    {
        //消息预留
        //发生异常，系统信息文件不存在，请查看
    }
}

int GlobalManager::updateDataLevel3(UpdateDataLv3 &updateDataLv3)
{
    usingMutex.lock();
    getAllTime();

    updateDataLv3.powerOnTime =  systemOnTimeStr.toStdString();
    updateDataLv3.totalPowerOnTime = totalSystemOnTimeStr.toStdString();
    updateDataLv3.totalStartMachineOnTime = totalStartMachineTimeStr.toStdString();
    updateDataLv3.servoOnTime = systemOnTimeStr.toStdString();
    updateDataLv3.globalRegister = globalRegister->getValues().toStdVector();

    usingMutex.unlock();
    return 1;
}

QString GlobalManager::pixmapTostring( const QPixmap& pixmap )
{
  QByteArray byte_array;
  QDataStream data_stream(&byte_array,QIODevice::WriteOnly);
  data_stream<<pixmap;
  QString res = QString::fromLocal8Bit(byte_array.toBase64());
  return res;
}

QPixmap  GlobalManager::stringTopixmap( const QString& pic )
{
  QByteArray byte_array = QByteArray::fromBase64(pic.toLocal8Bit());
  QPixmap pix;
  QDataStream data_stream(&byte_array,QIODevice::ReadOnly);
  data_stream>>pix;
  return pix;
}



int GlobalManager::getImageStringFromPath(QString filePath, QString &imageStringOut)
{

    QPixmap tmpMap;
    tmpMap.load(filePath);
    imageStringOut=pixmapTostring(tmpMap);
    return 1;
}
int GlobalManager::get_Control_IO_NamesInfo(const int &robotIdIn, const int &IOvalueType, std::vector<string> &namesOut)
{
    int errorCode = 0;
    bool ok = false;
    DomParser domParser;
    QString xmlfile = QString(D_TCRCONTROLLER_DATA_PATH)+QString(ROBOT_COMMON_NAME)
            + QString::number(robotIdIn) + QString(CONFIG_STRING) + "iomap.xml";


    ok = domParser.openXml(xmlfile, QFile::ReadOnly | QFile::Text);

    if(!ok)
    {
        qDebug()<< "ERROR: openXml :"  << xmlfile;
        errorCode = -1;
        return errorCode;
    }

    do
    {
        QString ioDataMap = "";

        QString diName = "";
        int logicValueIndex = 0;
        QDomNode noteItem =  domParser.getRootDomElement().firstChild();
        while (!noteItem.isNull ()) {

            if (noteItem.isElement ()) {

                //将其转换为元素

                diName = "";
                QDomElement elementItem = noteItem.toElement ();

                //返回元素标记和id属性的值，tagName()来获取元素节点的标签名，attribute()来获取元素节点指定的属性的值，

                qDebug()<<elementItem.text() << elementItem.tagName ();

                if(elementItem.tagName().compare("IO") == 0)
                {
                    if(elementItem.attribute("valueType").toInt() == IOvalueType)
                    {
                        diName=elementItem.text();

                        logicValueIndex = elementItem.attribute("logicValueIndex").toInt();
                        if(logicValueIndex>0)
                        {
                            if(logicValueIndex >= namesOut.size())
                            {
                                namesOut.resize(logicValueIndex);
                            }
                            logicValueIndex -= 1;
                            namesOut[logicValueIndex] = diName.toStdString();
                        }
                    }
                }
            }
            noteItem = noteItem.nextSibling ();//nextSibling()获取下一个兄弟节点
        }
    }
    while(0);
    closeXml();
    return errorCode;
}

int GlobalManager::playSystemMusic(QString musicFileName)
{
    #ifdef D_USE_ROS
    // 终止之前音乐进程
    system("killall -9 madplay &");
    // 循环播放
    QString errorFilePath=SYSTEM_MUSIC_FILEPATH;;
    errorFilePath+=musicFileName;
    QString musicCommand=(QString("%1%2%3%4")
                          .arg("madplay -a ")
                          .arg(QString::number(D_MUSIC_VOLUME))
                          .arg(" " + errorFilePath)
                          .arg(" &"));//-r ,不要循环播放了．
    qDebug()<<musicCommand;

    system(musicCommand.toLatin1().data());
    #endif
    return 1;
}

void GlobalManager::readRegRValue_fromFile()
{
    QString tmpFilePath=D_TCRCONTROLLER_DATA_PATH;
    QString regRName = tmpFilePath+GLOBAL_REG_R_FILE;
    //预留ｍｄ５校验

#if MD5CHECK_DEBUG
    if(md5Instance->compareMd5(regRName,GLOBAL_FILE_VALUE))
    {
        readRegRFile(regRName);
    }
    else
    {
        regRValue.resize(200);
    }
#else
//    readRegRFile(regRName);

   globalRegister-> readRegRFile_json(regRName);
#endif

}

//void GlobalManager::readRegRFile(QString fileName)
//{
//    QFile file(fileName);
//    if(file.exists())
//    {
//        if(file.open(QIODevice::ReadOnly))
//        {
//            QDataStream out(&file);
//            out.setVersion(QDataStream::Qt_4_6);
//            out >> regRValue;
//            file.close();
//            file.flush();//必须加，如果不加，可能关机的时候丢失文件内容。
//        }
//    }
//    else
//    {
//        regRValue.resize(200);
//    }
//}

void GlobalManager::saveRegRValue(QVector<double> tmpRValue)
{
    globalRegister->saveRegRValue(tmpRValue);
}

//void GlobalManager::writeRegR2File()
//{
//    qDebug() << "GlobalManager::writeRegR2File()";
//    for(int i = 0; i < regRValue.size();i++)
//    {
//        //std::cout << "---tmpRValue----"<<regRValue[i]<<std::endl;
//    }

//    QString tmpFilePath=D_TCRCONTROLLER_DATA_PATH;
//    QString regRName = tmpFilePath+GLOBAL_REG_R_FILE;


//    qDebug() << "===regRName===="<<regRName<<endl;

//    QFile file(regRName);
//    if(!file.open(QIODevice::ReadWrite))
//    {
//        //消息预留
//        //保存Ｒ寄存器数据失败
//    }
//    else
//    {
//        QDataStream out(&file);

//        out << regRValue;

//        file.close();
//        file.flush();//必须加，如果不加，可能关机的时候丢失文件内容。
//    }

// //   md5Instance.saveFile(regRName);
//}


void GlobalManager::writeAllRegFile()
{
//    writeRegR2File();
    QString tmpFilePath=D_TCRCONTROLLER_DATA_PATH;
    tmpFilePath = tmpFilePath+GLOBAL_REG_R_FILE;

    globalRegister-> writeRegR2File_json(tmpFilePath);
}

void GlobalManager::clearRegRValue()
{

      globalRegister->clearRegRValue();
}

int GlobalManager::saveRegRValue(int regNumber, float regValue)
{

    return globalRegister->saveRegRValue(regNumber,regValue);

}



void GlobalManager::realTimeSleep(long long microsecond)
{
    // 发送qt事件
    QCoreApplication::processEvents();

    struct timespec t;
    clock_gettime(CLOCK_REALTIME,&t);
    t.tv_nsec += microsecond * 1000;
    while(t.tv_nsec >= NSEC_PER_SEC)
    {
        t.tv_nsec -= NSEC_PER_SEC;
        ++t.tv_sec;
    }
    clock_nanosleep(CLOCK_REALTIME,TIMER_ABSTIME,&t,NULL);

}
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
void* GlobalManager::threadRun(void *)
{
    printf("globalManager theread start run !!!");
#if 0
    int max_cpus = sysconf(_SC_NPROCESSORS_ONLN);
    printf("Max CPUs = %d\n", max_cpus);

    /* lock all memory (prevent swapping) */
    if (mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
        printf("printf: mlockall\n");
    }

    set_latency_target();
    set_cpu(0);
#endif

    struct sched_param param;
    param.__sched_priority = 0;
    sched_setscheduler(0,SCHED_OTHER,&param);
    qDebug()<<"************************GlobalManager pid="<<gettid();
    usleep(287000);
    //setStackSize(81920);
    int policy, priority;
    pthread_getschedparam(pthread_self(), &policy, (struct sched_param *)&priority);
//    if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
//        qDebug("mlockall failed");
//    }
//    clock_gettime( CLOCK_MONOTONIC, &cycleTimespec );
    threadFunFlag=true;
   // qDebug()<<"this=="<<this;
//    QTime time;
//    time.start();
    int licenseCheckCount=1;

    while(threadFunFlag)
    {
        static int tmpTickCount=0;
        sleep(6);
       // realTimeSleep(3000);

//        checkResources(); cpu and ram coredump
        batteryMonitorLoop();

        if(NULL!=p_powerManger)
        {
            if(tmpTickCount<1000)
            {
                tmpTickCount++;
            }
//            if(tmpTickCount>10)
//            {
                p_powerManger->writePathMovingInfo();
//                qDebug()<<"GlobalManager p_powerManger->writePathMovingInfo()";
//            }

        }


        //日志保存
        MessageLog::getInstance()->timerSaveLogToFile();

        //授权检查
       licenseCheckCount++;
       if(licenseCheckCount%1000==0)
       {
           if(D_PERIOD_CHECK_LICENSE)
           {
               checkLicense();
           }

       }

//       errorSoundMonitor();

    }
    printf("globalManager theread quit!!!");
}

void* GlobalManager::threadTask( void* classPtr )
{
    return ((GlobalManager*)classPtr)->threadRun(NULL);
}

void GlobalManager::createThread()
{
    int ret=pthread_create( &threadId, NULL, &GlobalManager::threadTask,this);
}

void GlobalManager::checkResources()
{  


    //printf("checkResources!!!");
    updateCpuInfo();
    updateHardDiskInfo();//对９９的ethercat 线程有影响，导致很大几十ms不确定性。
    updateRamInfo();
    if(hardDiskFree<HARD_DISK_FREE_ERROR)
    {
        robotManager->ceaseAllRobot();
        qDebug()<<"hardDiskFree<HARD_DISK_FREE_ERROR";
        addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7002,robotId, hardDiskFree);
    }
    else  if(hardDiskFree<HARD_DISK_FREE_WARN)
    {
        qDebug()<<"hardDiskFree<HARD_DISK_FREE_WARN";
        addMsg(ENUM_MSG_WARNING,"GlobalManager","GlobalManager",7003,robotId, hardDiskFree);
    }


    if(ramFree<RAM_FREE_ERROR)
    {
        robotManager->ceaseAllRobot();
        qDebug()<<"ramFree<RAM_FREE_ERROR";
        addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7000,robotId, ramFree);
    }
    else if(ramFree<RAM_FREE_WARN)
    {
        qDebug()<<"ramFree<RAM_FREE_WARN";
        addMsg(ENUM_MSG_WARNING,"GlobalManager","GlobalManager",7001,robotId, ramFree);
    }



}


void GlobalManager::addMsg(int messageLevel, std::string componentName, std::string messageType, int messageCode, int robotIdIn
                              , int parameter1)
{
    Message tmpMsg;
    tmpMsg.MessageLevel = messageLevel;
    tmpMsg.componentClassName = componentName;
    tmpMsg.messageCode = messageCode;
    tmpMsg.messageType = messageType;
    tmpMsg.robotId = robotIdIn;

    string infomationStr;

    switch(messageCode)
    {
    case 7017:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")设备非授权状态，不允许修改系统时间！").toStdString();
       infomationStr = str1;
       break;
    }
    case 7016:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")设备时间系统出错！").toStdString();
       infomationStr = str1;
       break;
    }
    case 7015:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")设备授权天数剩余%1天！").arg(parameter1).toStdString();
       infomationStr = str1;
       break;
    }
    case 7014:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")电池电量不足，需要充电！").toStdString();
       infomationStr = str1;
       break;
    }
    case 7013:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")电池通讯错误！重试次数").toStdString()+QString::number(parameter1).toStdString();
       infomationStr = str1;
       break;
    }
    case 7012:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")用户强制程序退出！").toStdString();
       infomationStr = str1;
       break;
    }
    case 7011:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")电池电量告警，即将%1秒后关机！").arg(parameter1).toStdString();
       infomationStr = str1;
       break;
    }
    case 7010:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")电池进入保护状态！保护码").toStdString()+QString::number(parameter1).toStdString();
       infomationStr = str1;
       break;
    }
    case 7009:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")电池通信失败！").toStdString();
       infomationStr = str1;
       break;
    }
    case 7008:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")电池监视模块初始化失败！").toStdString();
       infomationStr = str1;
       break;
    }
    case 7007:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")系统正在重启，请等待！").toStdString();
       infomationStr = str1;
       break;
    }
    case 7006:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")启动方式不支持，请修改！").toStdString();
       infomationStr = str1;
       break;
    }

    case 7005:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")机器人正在关机，１０秒后关闭电源！").toStdString();
       infomationStr = str1;
       break;
    }

    case 7004:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")机器人程序正在运行，请先停止所有机器人，然后执行关机操作！").toStdString();
       infomationStr = str1;
       break;
    }

    case 7003:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")硬盘剩余不足:").toStdString()+
               QString::number(parameter1).toStdString() +
               QObject::tr("MB").toStdString();
       infomationStr = str1;
       break;
    }
    case 7002:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")硬盘剩余不足:").toStdString()+
               QString::number(parameter1).toStdString() +
               QObject::tr("MB").toStdString();
       infomationStr = str1;
       break;
    }
    case 7001:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")RAM剩余不足:").toStdString()+
               QString::number(parameter1).toStdString() +
               QObject::tr("MB").toStdString();
       infomationStr = str1;
       break;
    }
    case 7000:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")RAM剩余不足:").toStdString()+
               QString::number(parameter1).toStdString() +
               QObject::tr("MB").toStdString();
       infomationStr = str1;
       break;
    }
    case 1000:
    {
       string str1;
       str1 = QObject::tr("机器人(ID:").toStdString() +
               QString::number(robotIdIn).toStdString() +
               QObject::tr(")").toStdString() +
               QObject::tr("RAM剩余不足").toStdString();
       infomationStr = str1;
       break;
    }




        default:
        {
            qDebug()<<"Coordinate::addMsg====not match error code";
            break;
        }
    }

    tmpMsg.MessageInformation = infomationStr;

    //#ifndef MOTION_SERVER_UNIT_TEST
    //motionMessage->addMsg(tmpMsg);
    MessageLog::getInstance()->addMessage(tmpMsg);
    //#endif
}

int GlobalManager::batteryMonitorLoop()
{
    if(NULL==batteryMonitor)
    {
        return 0;
    }
    BatteryInformation tmpBatteryInfoOut;
    int tmpKey=batteryMonitor->getBatteryInfo(tmpBatteryInfoOut);
    if(0>tmpKey)
    {
        qDebug()<<"error, batteryMonitor  error";
        addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7013,robotId,-tmpKey);
        return -1;
    }
    else if(0==tmpKey)
    {
        return 1;
    }

    //如果电池报错，就不要关机。
    if(0!=tmpBatteryInfoOut.errorStatus)
    {
        qDebug()<<"error, batteryMonitor  safe error";
        addMsg(ENUM_MSG_WARNING,"GlobalManager","GlobalManager",7010,robotId,tmpBatteryInfoOut.errorStatus);
        return -2;
    }

    //shutdown monitor
    E_BATTERY_STATUS tmpStatus;
    static bool isPlayMusic=false;
    batteryMonitor->getBatteryStatus(tmpStatus);
    if(E_BATTERY_STATUS_SHUTDOWN==tmpStatus)
    {
        double tmpDelay=batteryMonitor->getShutdownDelaySeconds();
        qDebug()<<"error, battery voltage too low";
        addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7011,-1,tmpDelay);
        playSystemMusic("batteryDown.mp3");
        sleep(tmpDelay);
        controllerShutDown();
    }
    else if(E_BATTERY_STATUS_WARNNING==tmpStatus)
    {
        if(false==isPlayMusic)
        {
           playSystemMusic("batteryWarn.mp3");
           isPlayMusic=true;
        }

        qDebug()<<"warnning, battery voltage too low";
        addMsg(ENUM_MSG_WARNING,"GlobalManager","GlobalManager",7014,-1);
    }
    else
    {
        isPlayMusic=false;
    }


    return 1;
}



int GlobalManager::checkLicense()
{
  qDebug()<<"checkLicense11111111";
  int dateLefted=100;
  if(NULL!=p_powerManger)
  {
    dateLefted=p_powerManger->getLicenseDayLefted();
  }
  if(dateLefted<7)
  {
      addMsg(ENUM_MSG_REMIND,"GlobalManager","GlobalManager",7015,-1,dateLefted);
      #ifdef D_USE_ROS
      // 终止之前音乐进程
      system("killall -9 madplay &");
      // 循环播放
      QString warnningFilePath=SYSTEM_MUSIC_FILEPATH;
      warnningFilePath+="licenseGoingPass.mp3";
      system((QString("%1%2%3%4")
              .arg("madplay -a ")
<<<<<<< HEAD
              .arg(QString::number(D_MUSIC_VOLUME))
=======
              .arg(QString::number(15))
>>>>>>> origin/master
              .arg(" " + warnningFilePath)
              .arg(" -r &")).toLatin1().data());
        #endif
  }
  else if(dateLefted<=0)
  {
      addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7015,-1,dateLefted);
      #ifdef D_USE_ROS
      // 终止之前音乐进程
      system("killall -9 madplay &");
      // 循环播放
      QString passedFilePath=SYSTEM_MUSIC_FILEPATH;;
      passedFilePath+="licensePassed.mp3";
      system((QString("%1%2%3%4")
              .arg("madplay -a ")
<<<<<<< HEAD
              .arg(QString::number(D_MUSIC_VOLUME))
=======
              .arg(QString::number(15))
>>>>>>> origin/master
              .arg(" " + passedFilePath)
              .arg(" -r &")).toLatin1().data());
       #endif
  }
  if(1!=isDateHistoryCorrect())
  {
      addMsg(ENUM_MSG_ERROR,"GlobalManager","GlobalManager",7016,-1);
  }
  saveDateToXmlFile(D_DATE_LOG_PATH);
  return 1;
}


int GlobalManager::initial_forDateFileFialed(QString xmlLogFileNameIn)
{
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString newFileName=xmlLogFileNameIn+current_date_time.toString("yyyy.MM.dd-hh:mm:ss");
    QFile::rename(xmlLogFileNameIn,newFileName);

    QFile file(xmlLogFileNameIn);
    //定义文件内容字符串
    QString content= "<common>  <log>  </log>  </common>";
    //判断文件是否存在
    if(file.exists())
    {
    }else
    {
        //存在打开，不存在创建
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        //写入内容,这里需要转码，否则报错。
        QByteArray str = content.toUtf8();
        //写入QByteArray格式字符串
        file.write(str);

    }
    //关闭文件
    file.close();
    return 1;

}

int GlobalManager::isDateHistoryCorrect()
{
    for(int i=0;i<historyRecordTime.size()-1;i++)
    {
        if(historyRecordTime[i+1]<=historyRecordTime[i])
        {
            qDebug()<<"historyRecordTime[i+1] "<<historyRecordTime[i+1]
                   <<"historyRecordTime[i] "<<historyRecordTime[i] ;
            return -1;
        }
    }
    return 1;
}

int GlobalManager::saveDateToXmlFile(QString xmlLogFileName)
{
//    qDebug() << "GlobalManager::saveDateTo begin,,,";
    DomParser domParser;
    bool ok = domParser.openXml(xmlLogFileName, QIODevice::ReadWrite );
    if( !ok )//无法打开机器人数据文件！
    {
        domParser.closeXml();
        initial_forDateFileFialed(xmlLogFileName);
        qDebug()<<"error date logFile not exist！";
        return -1;
    }

    ///读参数
    QDomNode  mainNode = domParser.findSubNode(domParser.getRootDomElement(), "log", ok );
    if( !ok )
    {
       qDebug()<<"error no log node";
        return -1;
    }

    struct timespec nowTime;
    clock_gettime(CLOCK_REALTIME, &nowTime);//
    long tmpTimeLong = nowTime.tv_sec;
    historyRecordTime.append(tmpTimeLong);

    time_t timep;//
    struct tm* p;
    timep = tmpTimeLong;  //
    p=localtime(&timep);//从tm结构体中可以取到年月日时分秒等值。
    char szTmp[50] = {0};
    strftime(szTmp,50,"%Y-%m-%d %H:%M:%S",p);    //这里输出的将是 p的时间值
    QString strTime = QString(QLatin1String(szTmp));

    domParser.addNode(mainNode,"record","");
    QDomNode  recordNode;
    QDomNodeList devNodes = mainNode.childNodes();
    recordNode=devNodes.at(devNodes.size()-1);
    domParser.addNode(recordNode,"timeLong",tmpTimeLong);
    domParser.addNode(recordNode,"timeString",strTime);

    domParser.closeXml(true);//保存
//    qDebug() << "GlobalManager::saveDate end";


    return 1;
}

int GlobalManager::readDateFromXmlFile(QString xmlLogFileName)
{
    qDebug() << "GlobalManager::readDate" ;

    DomParser domparser;
    bool ok = domparser.openXml(xmlLogFileName, QIODevice::ReadOnly);
    if( !ok )
    {
        if(IF_DEBUG)
        {
            qDebug() << "文件打开失败：" ;
        }
        return -1;
    }

    QDomNode domNode = domparser.findSubNode(domparser.getRootDomElement(), "log", ok );
    if( !ok )
    {
        if(IF_DEBUG)
        {
            qDebug() << "结点失败：" ;
        }
            return -2;
    }

    QDomNodeList posNodeList=domNode.childNodes();

    long timeTime;
    for(int i=0;i<posNodeList.size();i++)
    {
        // 读取positionType
        domparser.readXml(domparser.findSubNode(posNodeList.at(i), "timeLong", ok ), timeTime);
        if( !ok )
        {
                return -3;
        }
        historyRecordTime.append(timeTime);

    }

    domparser.closeXml();
    return 1;
}


int GlobalManager::errorSoundMonitor()
{
    if(1!=isPlaySoudOnError)
    {
        return -1;
    }
//    qDebug()<<"errorSoundMonitor2222222";
    static bool isPlayed=false;
    if(true==MessageLog::getInstance()->isErrorOccured() && false==isPlayed)
    {
        #ifdef D_USE_ROS
        // 终止之前音乐进程
        system("killall -9 madplay &");
        // 循环播放
        QString errorFilePath=SYSTEM_MUSIC_FILEPATH;;
        errorFilePath+="error.mp3";
        QString musicCommand=(QString("%1%2%3%4")
                              .arg("madplay -a ")
<<<<<<< HEAD
                              .arg(QString::number(D_MUSIC_VOLUME))
=======
                              .arg(QString::number(12))
>>>>>>> origin/master
                              .arg(" " + errorFilePath)
                              .arg(" -r &"));
        qDebug()<<musicCommand;

        system(musicCommand.toLatin1().data());
        #endif
        isPlayed=true;
    }
    else if(false==MessageLog::getInstance()->isErrorOccured() && true==isPlayed)
    {
        #ifdef D_USE_ROS
        // 终止之前音乐进程
        system("killall -9 madplay &");
        #endif
        isPlayed=false;
    }
    return 1;
}


